//
//  SplashManager.m
//  coldjoke-ios-client
//
//  Created by lai on 13-2-19.
//
//

#import "SplashManager.h"
#import "FileManager.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "NetWorkManager.h"
#import "SBJsonParser.h"
#import "RegexKitLite.h"

//#define SPLASH_IMAGE_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/WelcomeImage"]

@implementation SplashManager
SYNTHESIZE_SINGLETON_FOR_CLASS(SplashManager);

-(id)init{
    self = [super init];
    scanLocalSplashImages = [[[FileManager sharedInstance] scanLocalSplashImages]retain];
    localSplashImageList = [[NSMutableSet setWithArray:[scanLocalSplashImages sortedArrayUsingSelector:@selector(compare:)]]retain];
    return self;
}

- (NSString *)getSplashImageName {
    //获取今天的日期,时间格式： splash2013-03-06-v1.jpg 
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];  
    today = [NSString stringWithFormat:@"splash%@",[dateFormatter stringFromDate:[NSDate date]]];
    NSLog(@"today is :%@",today);
    NSString *searchString = @"";
    for (int i = 0; i < scanLocalSplashImages.count; i++) {
        searchString = [NSString stringWithFormat:@"%@,%@",[scanLocalSplashImages objectAtIndex:i],searchString];
    }
    NSString *result = [self matchToday:today andSearchString:searchString];
    NSString *info = nil;
    if (result == NULL) {
        info = @"false";
    }else{
        info = result;
    }
    return info;
}

- (NSString *)getImageName:(NSString *)url{
    NSArray *urlArray = [url componentsSeparatedByString:@"/"];
    NSString *name = [NSString stringWithFormat:@"%@",[urlArray objectAtIndex:[urlArray count]-1]];
    return name;
}

//传进去：splash2013-03-06-v1.jpg ,返回splash2013-03-06
- (NSString *)getImageDate:(NSString *)name {
    NSString * str = [name stringByMatching:@"(splash.*?)-v\\d+(?=.jpg)" capture:1];
    return str;
}

- (NSString *)matchToday:(NSString *)splashToday andSearchString:(NSString *)search{
    NSString *machting = [NSString stringWithFormat:@"%@-v\\d+?.jpg",splashToday];
    NSString * result = [search stringByMatching:machting];
    return result;
}

//传进去：splash2013-03-06-v1.jpg ,返回1
- (int)getImageVersion:(NSString *)original{
    int version = [[original stringByMatching:@"\\d+(?=.jpg)"] intValue];
    return version;
}

//在子线程里面执行
- (void)downloadSplashImages {
    NSMutableSet *remoteSplashImageUrl = [self httpGetFestivalImage];
    NSLog(@"remoteSplashImageUrl :%@",remoteSplashImageUrl);
    if (remoteSplashImageUrl == nil) {
        return;
    }
    
    NSLog(@"before localSplashImageList:%@",localSplashImageList);

    if (localSplashImageList.count == 0) {
        for (NSString *one in remoteSplashImageUrl.allObjects) {
            NSLog(@"one :%@",one);
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:one]];
            [[FileManager sharedInstance]saveSplashImage:imageData withUrl:one];
        }
    }else{
        //浏览本地的放入字典
        NSMutableDictionary *localDict = [[NSMutableDictionary alloc]init];
        if (scanLocalSplashImages == NULL) {
            scanLocalSplashImages = [[FileManager sharedInstance] scanLocalSplashImages];
        }
        
        for (int i = 0; i < scanLocalSplashImages.count; i++) {
            NSString *date = [self getImageDate:[scanLocalSplashImages objectAtIndex:i]];
            [localDict setValue:[scanLocalSplashImages objectAtIndex:i] forKey:date];
        }
        
        //开始过滤线上的图片
        for (NSString *one in remoteSplashImageUrl.allObjects) {
            NSString *remoteImageName = [self getImageName:one];
            NSString *remoteImageDate = [self getImageDate:remoteImageName];
            if ([localDict objectForKey:remoteImageDate]) {
                int remoteVersion = [self getImageVersion:remoteImageName];
                int localVersion = [self getImageVersion:[localDict objectForKey:remoteImageDate]];
                if (remoteVersion == localVersion) {
                    continue;
                }else if(remoteVersion > localVersion){
                    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:one]];
                    [[FileManager sharedInstance]deleteFile:[localDict objectForKey:remoteImageDate]];
                    [[FileManager sharedInstance]saveSplashImage:imageData withUrl:one];
                }
            }else{
                NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:one]];
                [[FileManager sharedInstance]saveSplashImage:imageData withUrl:one];
            }
        }
        
        
        [localDict release];
        
        NSMutableSet *remoteImageNames = [[NSMutableSet alloc]init];
        for (NSString *one in remoteSplashImageUrl.allObjects) {
            NSString *remoteImageName = [self getImageName:one];
            [remoteImageNames addObject:remoteImageName];
        }
        
        for (NSString *one in localSplashImageList.allObjects) {
            NSString *localImageName = [self getImageName:one];
            if ([remoteImageNames containsObject:localImageName]) {
                continue;
            }else{
                [[FileManager sharedInstance] deleteWelcomeFile:one];
            }
        }
        [remoteImageNames release];
    }
}

/*
 http://192.168.37.129/a.php
 
 {"resp": {"url": "http://service.androidesk.com/static/", "pics": ["splash2013-03-06-v1.jpg","splash2013-03-07-v2.jpg"]}}
  */

-(NSMutableSet *)httpGetFestivalImage{
    NSString *url = splashUrlImage;
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    request.userAgentString = userAgentValue;
    [request setRequestMethod:@"GET"];
    [request setAllowCompressedResponse:YES];
    [request setUseCookiePersistence:YES];
    [request setDelegate:self];
    [request startSynchronous];
//    ASIHttpRequset_GET(url, NO);
    NSError *error = [request error];
    NSMutableArray *res = nil;
    if(!error){
        res = [self requestLoginDone:request];
    }else{
        res = nil;
    }
    NSMutableSet *set = [NSMutableSet setWithArray:[res sortedArrayUsingSelector:@selector(compare:)]];
    return set;
}

- (NSMutableArray *)requestLoginDone:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    NSMutableArray *res = [[[NSMutableArray alloc]init]autorelease];

    NSLog(@"tResponseStr :%@",tResponseStr);
    SBJsonParser *tJsonParser = [[SBJsonParser alloc] init];
    id tJsonObjects = [tJsonParser objectWithString:tResponseStr];
    NSLog(@"tjson:%@",tJsonObjects);
    PP_RELEASE(tJsonParser);
    if ([tJsonObjects isKindOfClass:[NSDictionary class]]){
        NSDictionary *dict =[tJsonObjects objectForKey:@"resp"];        
        NSArray *arr = [dict objectForKey:@"pics"];
        NSString *urlPrex = [dict objectForKey:@"url"];
        for (int i = 0; i < arr.count; i++) {
            if (![[arr objectAtIndex:i] isMatchedByRegex:@"^splash\\d{4}-\\d{2}-\\d{2}-v\\d+.jpg$"]){
                continue;
            }
            NSLog(@"===========%@%@",urlPrex,[arr objectAtIndex:i]);
            [res addObject:[NSString stringWithFormat:@"%@%@",urlPrex,[arr objectAtIndex:i]]];
        }
    }else{
        res = nil;
        Log ( @"failed : response parse failed");
    }
    return res;
}

//NSMutableSet *set = [NSMutableSet setWithArray:[res sortedArrayUsingSelector:@selector(compare:)]];

- (void)requestLoginWentWrong:(ASIHTTPRequest *)request
{
    NSString *tResponseStr = [request responseString];
    Log(@"res : %@",tResponseStr);
    NSError *error = [request error];
    Log(@"failed : %@",[error description]);
}

- (void) dealloc {
    PP_RELEASE(localSplashImageList);
    PP_RELEASE(scanLocalSplashImages);
    PP_RELEASE(today);
    [super dealloc];
}

@end
